package com.smartlbs.controller;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smartlbs.baseframe.web.ResponseInfo;
import com.smartlbs.quartz.QuartzJob;
import com.smartlbs.quartz.QuartzManagerServiceImpl;
import com.smartlbs.quartz.QuartzMangerService;
import com.smartlbs.service.ISettingService;

/**
 * 定制频率控制层类
 * 
 * @author idaowei
 *
 */
@Controller
@RequestMapping("adminuser/quartz")
public class SysQuartzController {
	@Autowired
	private QuartzMangerService quartz;
	
	@Autowired
	private ISettingService settingService;
	/**
	 * 开启/修改一个定时任务
	 * 
	 * @param corn
	 */
	@RequestMapping("do")
	@ResponseBody
	public ResponseInfo doquartz(HttpServletRequest request, Integer time) {
		ResponseInfo responseInfo = new ResponseInfo();
		int result = 0;
		String message = "";
		Object data = null;
		Integer hours = null;
		String cron = "0 0 0/1 * * ? ";
		if (time == null || time >= 1440 || time < 0) {
			message = "输入有误，请重新输入";
			result=-1;
			responseInfo.setData(data);
			responseInfo.setMessage(message);
			responseInfo.setResult(result);
			return responseInfo;
		}

		if (time < 60) {
			cron = "0 0/" + time + " * * * ?";
		} else {
			if(time%60<30){
				hours = time / 60;
			}else {
				hours=time/60+1;
			}
			cron = "0 0 0/" + hours + " * * ? ";
		}

		try {
			String jobName = "jobName";
			String jobGroupName = "jobGroupName";
			String triggerName = "triggerName";
			String triggerGroupName = "triggerGroupName";

			// 移除一个定时任务
			quartz.removeJob(jobName, jobGroupName, triggerName,
					triggerGroupName);
			// 开启一个默认的定时任务
			quartz.addJob(jobName, jobGroupName, triggerName, triggerGroupName,
					QuartzJob.class, cron, null);
			settingService.setting(3, String.valueOf(time));
			message = "修改成功";
			result = 1;
		} catch (Exception e) {
			message = "发生异常";
			result = -2;
			// TODO: handle exception
		}
		responseInfo.setData(data);
		responseInfo.setMessage(message);
		responseInfo.setResult(result);
		return responseInfo;
	}
}
